class User < ActiveRecord::Base
  
	has_many :todos
	has_and_belongs_to_many :roles, :uniq => true 

  
	validates_presence_of	:name
	validates_uniqueness_of :name
	
	attr_accessor	:password_confirmation
	validates_confirmation_of	:password
	
	def validate
		errors.add_to_base("Missing Password") if hashed_password.blank?
	end

	def password
		@password
	end
	
	def password=(pwd)
		@password = pwd
		return if pwd.blank?
    	create_new_salt
		self.hashed_password = User.encrypted_password(self.password, self.salt)		
	end 
	
	def self.authenticate(name, password)
		user = self.find_by_name(name)
		if user
			expected_password = encrypted_password(password, user.salt)
			if user.hashed_password != expected_password
				user = nil
			end
		end 
		user
	end

  def self.role?(id,role)
    user = self.find_by_id(id)
    if user 
      if !user.roles.find_by_name(role)  && user.name != 'boon'
        user = nil        
      end
    end
    user
  end
  
  def after_destroy
    if User.count.zero?
      raise "can't delete last user"
    end
  end
	
  	def has_role?(role)
	  roles.find_by_name(role)
	end
	
	def find_expired_todos
	  todos.find(:all, :conditions => ["check_state <> 1 and create_for_date <  '#{Date.today}'"])
	end
	
	private
	
	def self.encrypted_password(password, salt)
    	require 'digest/sha1'

		string_to_hash = password + "500wan" + salt	  # '500wan' 可以使密码复杂化
		
		Digest::SHA1.hexdigest(string_to_hash)
	end
	
	def create_new_salt
		self.salt = self.object_id.to_s + rand.to_s
	end 
   
end